package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.counseling.model.common.exception.ServiceException;
import com.campus.counseling.entity.*;
import com.campus.counseling.model.mapper.SysUserMapper;
import com.campus.counseling.model.dto.LoginDTO;
import com.campus.counseling.model.dto.ProfileUpdateDTO;
import com.campus.counseling.model.dto.RegisterDTO;
import com.campus.counseling.model.dto.UserDTO;
import com.campus.counseling.model.mapper.*;
import com.campus.counseling.model.query.UserQuery;
import com.campus.counseling.model.vo.LoginVO;
import com.campus.counseling.model.vo.UserVO;
import com.campus.counseling.security.JwtTokenUtil;
import com.campus.counseling.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Service
@RequiredArgsConstructor
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    private final PasswordEncoder passwordEncoder;
    private final SysUserMapper userMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysRoleMapper roleMapper;
    private final CounselorMapper counselorMapper;
    private final SysRegisterStatsMapper registerStatsMapper;
    private final SysRegisterLogMapper registerLogMapper;
    private final StudentMapper studentMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 查询用户
        SysUser user = userMapper.selectOne(
            new QueryWrapper<SysUser>()
                .eq("username", loginDTO.getUsername())
        );
        
        // 用户不存在
        if (user == null) {
            throw new ServiceException("用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }

        // Spring Security认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成token，支持记住我功能
        String token = jwtTokenUtil.generateToken(authentication, loginDTO.getRemember() != null && loginDTO.getRemember());

        return new LoginVO(token);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userMapper.selectCount(new QueryWrapper<SysUser>()
                .eq("username", registerDTO.getUsername())) > 0) {
            throw new ServiceException("该用户名已被注册");
        }

        // 检查手机号是否已存在
        if (userMapper.selectCount(new QueryWrapper<SysUser>()
                .eq("phone", registerDTO.getPhone())) > 0) {
            throw new ServiceException("该手机号已被注册");
        }

        // 检查邮箱是否已存在
        if (userMapper.selectCount(new QueryWrapper<SysUser>()
                .eq("email", registerDTO.getEmail())) > 0) {
            throw new ServiceException("该邮箱已被注册");
        }

        LocalDateTime now = LocalDateTime.now();  // 获取当前时间
        Long userId;
        String username = registerDTO.getUsername();
        SysUser user = new SysUser(); // 创建 SysUser 对象

        // 如果是咨询师注册
        if ("counselor".equals(registerDTO.getRole())) {
            // 创建咨询师信息
            Counselor counselor = new Counselor();
            BeanUtils.copyProperties(registerDTO, counselor);
            counselor.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
            counselor.setStatus("PENDING");
            counselor.setCreateTime(now);        // 设置创建时间
            counselor.setUpdateTime(now);        // 设置更新时间
            counselorMapper.insert(counselor);
            userId = counselor.getId();

            // 同时创建用户记录
            BeanUtils.copyProperties(registerDTO, user);
            user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
            user.setStatus(0); // 待审核状态
            user.setCreateTime(now);
            user.setUpdateTime(now);
            userMapper.insert(user);
        } else {
            // 普通用户注册
            BeanUtils.copyProperties(registerDTO, user);
            user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
            user.setStatus(1);
            user.setCreateTime(now);            // 设置创建时间
            user.setUpdateTime(now);            // 设置更新时间
            userMapper.insert(user);
            userId = user.getId();

            // 分配角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(getRoleId(registerDTO.getRole()));
            userRole.setCreateTime(now);        // 设置创建时间
            userRoleMapper.insert(userRole);

            // 如果是学生角色，创建学生信息记录
            if ("student".equals(registerDTO.getRole())) {
                Student student = new Student();
                student.setUserId(userId);
                // 其他字段为空，等待用户后续完善
                studentMapper.insert(student);
            }
        }

        // 保存注册日志
        saveRegisterLog(userId, username, registerDTO.getRole(), "SUCCESS");
        
        // 更新注册统计
        updateRegisterStats(registerDTO.getRole());
    }

    /**
     * 更新注册统计
     */
    private void updateRegisterStats(String role) {
        try {
            LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            
            // 查找今天的统计记录
            SysRegisterStats stats = registerStatsMapper.selectOne(
                new LambdaQueryWrapper<SysRegisterStats>()
                    .eq(SysRegisterStats::getStatDate, today)
            );
            
            if (stats == null) {
                // 如果没有今天的记录，创建新记录
                stats = new SysRegisterStats();
                stats.setStatDate(today);
                stats.setStudentCount(0);
                stats.setCounselorCount(0);
                stats.setTotalCount(0);
                stats.setCreateTime(LocalDateTime.now());
                stats.setUpdateTime(LocalDateTime.now());
                
                // 根据角色设置初始计数
                if ("student".equals(role)) {
                    stats.setStudentCount(1);
                } else if ("counselor".equals(role)) {
                    stats.setCounselorCount(1);
                }
                stats.setTotalCount(stats.getStudentCount() + stats.getCounselorCount());
                
                // 插入新记录
                registerStatsMapper.insert(stats);
            } else {
                // 已有记录，执行更新
                if ("student".equals(role)) {
                    stats.setStudentCount(stats.getStudentCount() + 1);
                } else if ("counselor".equals(role)) {
                    stats.setCounselorCount(stats.getCounselorCount() + 1);
                }
                stats.setTotalCount(stats.getStudentCount() + stats.getCounselorCount());
                stats.setUpdateTime(LocalDateTime.now());
                
                // 更新记录
                registerStatsMapper.updateById(stats);
            }
            
            log.info("更新注册统计成功: role={}, date={}", role, today);
        } catch (Exception e) {
            log.error("更新注册统计失败: role={}, error={}", role, e.getMessage());
            // 这里不抛出异常，避免影响主流程
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long userId, String password) {
        // 检查用户是否存在
        SysUser user = getById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 加密新密码
        String encodedPassword = passwordEncoder.encode(password);
        
        // 更新密码
        user.setPassword(encodedPassword);
        updateById(user);
        
        log.info("用户密码重置成功，用户ID：{}", userId);
    }

    @Override
    public SysUser getCurrentUser() {
        // 获取当前用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 获取当前用户名
        String username = authentication.getName();
        // 根据用户名查询用户信息
        return getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
    }

    @Override
    public UserVO getCurrentUserInfo() {
        // 获取当前用户信息
        SysUser user = getCurrentUser();
        // 如果用户未登录，抛出异常
        if (user == null) {
            throw new ServiceException("用户未登录");
        }

        // 创建用户VO对象
        UserVO vo = new UserVO();
        // 将用户信息复制到VO对象中
        BeanUtils.copyProperties(user, vo);
        
        // 处理地区信息
        if (user.getRegion() != null && !user.getRegion().trim().isEmpty()) {
            // 如果地区信息不为空，则将地区信息设置到VO对象中
            vo.setRegion(user.getRegion());
        }

        return vo;
    }

    @Override
    public void logout() {
        // 清除当前用户的认证信息
        SecurityContextHolder.clearContext();
        // 如果使用了Redis存储token，这里还需要清除Redis中的token
    }

    @Override
    public Page<UserVO> getUserPage(UserQuery query) {
        log.info("开始查询用户列表: pageNum={}, pageSize={}", query.getPageNum(), query.getPageSize());

        try {
            // 创建分页对象
            Page<SysUser> page = new Page<>(query.getPageNum(), query.getPageSize());

            // 获取当前用户角色
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            log.info("查询用户列表 - 当前用户: {}", auth.getName());

            // 构建查询条件 - 查询sys_user表
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();

            // 按用户名模糊查询
            if (StringUtils.hasText(query.getUsername())) {
                wrapper.like(SysUser::getUsername, query.getUsername());
            }

            // 按角色查询 - 通过sys_user_role关联表查询
            if (StringUtils.hasText(query.getRole())) {
                List<Long> userIds = userMapper.selectUserIdsByRoleKey(query.getRole());
                if (!userIds.isEmpty()) {
                    wrapper.in(SysUser::getId, userIds);
                }
            }

            wrapper.orderByDesc(SysUser::getCreateTime);

            // 执行查询
            Page<SysUser> userPage = page(page, wrapper);
            log.info("查询到用户数据: records={}", userPage.getRecords().size());

            // 转换为VO
            Page<UserVO> voPage = new Page<>(query.getPageNum(), query.getPageSize());
            voPage.setTotal(userPage.getTotal());

            if (userPage.getRecords() != null && !userPage.getRecords().isEmpty()) {
                List<UserVO> voList = userPage.getRecords().stream().map(user -> {
                    UserVO vo = new UserVO();
                    BeanUtils.copyProperties(user, vo);

                    // 获取用户角色
                    String role = userMapper.selectUserRoles(user.getId()).toString();
                    vo.setRole(role);

                    return vo;
                }).collect(Collectors.toList());

                voPage.setRecords(voList);
            } else {
                voPage.setRecords(Collections.emptyList());
            }

            return voPage;
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            throw new ServiceException("查询用户列表失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserDTO userDTO) {
        // 检查用户名是否已存在
        if (userMapper.selectCount(new QueryWrapper<SysUser>()
                .eq("username", userDTO.getUsername())) > 0) {
            throw new ServiceException("该用户名已存在");
        }

        LocalDateTime now = LocalDateTime.now();
        
        // 创建用户
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        user.setStatus(1);
        user.setCreateTime(now);
        user.setUpdateTime(now);
        userMapper.insert(user);

        // 分配角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(getRoleId(userDTO.getRole()));
        userRole.setCreateTime(now);
        userRoleMapper.insert(userRole);

        // 如果是学生角色，创建学生信息记录
        if ("student".equals(userDTO.getRole())) {
            Student student = new Student();
            student.setUserId(user.getId());
            // 其他字段为空，等待用户后续完善
            studentMapper.insert(student);
            log.info("已创建学生记录: userId={}", user.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(Long id, UserDTO userDTO) {
        // 检查用户是否存在
        SysUser user = getById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 获取当前操作用户的角色和ID
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = auth.getName();
        SysUser currentUser = getByUsername(currentUsername);
        
        List<String> currentUserRoles = userMapper.selectUserRoles(currentUser.getId());
        boolean isSuperAdmin = currentUserRoles.contains("superadmin");
        boolean isAdmin = currentUserRoles.contains("admin");

        log.info("当前用户: {}, 角色: {}", currentUsername, currentUserRoles);
        
        // 检查用户名是否已被其他用户使用
        if (!user.getUsername().equals(userDTO.getUsername()) &&
                lambdaQuery().eq(SysUser::getUsername, userDTO.getUsername()).exists()) {
            throw new ServiceException("用户名已存在");
        }

        // 获取目标用户当前的角色
        List<String> targetUserRoles = userMapper.selectUserRoles(user.getId());
        boolean isTargetSuperAdmin = targetUserRoles.contains("superadmin");

        // 角色权限检查
        if (StringUtils.hasText(userDTO.getRole())) {
            // 如果是超级管理员，可以修改任何用户的角色，包括其他超级管理员
            if (isSuperAdmin) {
                log.info("超级管理员修改用户: {} -> {}", user.getUsername(), userDTO.getRole());
            }
            // 如果是普通管理员
            else if (isAdmin) {
                // 1. 不能修改超级管理员的信息
                if (isTargetSuperAdmin) {
                    throw new ServiceException("无权修改超级管理员信息");
                }
                
                // 2. 不能修改管理员的信息
                if (targetUserRoles.contains("admin")) {
                    throw new ServiceException("无权修改管理员信息");
                }
                
                // 3. 不能将用户角色提升为超级管理员或管理员
                if ("superadmin".equals(userDTO.getRole()) || "admin".equals(userDTO.getRole())) {
                    throw new ServiceException("无权设置该角色");
                }
                
                // 4. 普通管理员只能管理咨询师和学生角色
                if (!Arrays.asList("counselor", "student").contains(userDTO.getRole())) {
                    throw new ServiceException("无权设置该角色");
                }
            }
            // 其他角色无权修改用户角色
            else {
                throw new ServiceException("无权修改用户角色");
            }
        }

        // 更新用户信息时保留原密码
        String originalPassword = user.getPassword();  // 保存原密码
        BeanUtils.copyProperties(userDTO, user);
        if (!StringUtils.hasText(userDTO.getPassword())) {
            user.setPassword(originalPassword);  // 如果没有新密码，使用原密码
        } else {
            user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        }
        user.setUpdateTime(LocalDateTime.now());
        updateById(user);

        // 更新用户角色
        if (StringUtils.hasText(userDTO.getRole())) {
            // 1. 先删除用户所有角色
            userMapper.deleteUserRoles(user.getId());
            
            // 2. 添加新角色
            Long roleId = userMapper.selectRoleIdByRoleKey(userDTO.getRole());
            if (roleId != null) {
                log.info("更新用户角色关联: userId={}, roleId={}, role={}, operator={}", 
                    user.getId(), roleId, userDTO.getRole(), currentUsername);
                userMapper.insertUserRole(user.getId(), roleId);
            } else {
                log.warn("未找到对应的角色: {}", userDTO.getRole());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        SysUser user = getById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        try {
            // 删除用户角色关联
            userRoleMapper.deleteByUserId(id);
            
            // 使用 baseMapper 直接调用自定义的删除方法
            int rows = baseMapper.deleteById(id);
            
            if (rows == 0) {
                throw new ServiceException("删除用户失败");
            }
            
            log.info("用户删除成功: {}", id);
        } catch (Exception e) {
            log.error("删除用户失败: {}", e.getMessage(), e);
            throw new ServiceException("删除用户失败: " + e.getMessage());
        }
    }

    @Override
    public SysUser getByUsername(String username) {
        // 根据用户名查询用户
        return lambdaQuery()
                // 等于用户名
                .eq(SysUser::getUsername, username)
                // 返回一个用户
                .one();
    }

    // 判断用户名是否存在
    private boolean isUsernameExists(String username) {
        // 使用LambdaQueryWrapper查询SysUser表，判断用户名是否等于传入的username
        return count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username)) > 0;
    }

    // 检查用户名是否存在
    private void checkUsernameExists(String username) {
        // 如果用户名已存在，则抛出异常
        if (isUsernameExists(username)) {
            throw new ServiceException("用户名已存在");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProfile(Long id, ProfileUpdateDTO dto) {
        // 检查用户是否存在
        SysUser user = getById(id);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 检查用户名是否已存在（如果修改了用户名）
        if (!user.getUsername().equals(dto.getUsername())) {
            checkUsernameExists(dto.getUsername());
        }

        // 更新用户信息
        BeanUtils.copyProperties(dto, user);
        
        // 处理地区信息
        if (dto.getRegion() != null && !dto.getRegion().isEmpty()) {
            user.setRegion(String.join(",", dto.getRegion()));
        }

        // 更新时间
        user.setUpdateTime(LocalDateTime.now());

        // 保存更新
        updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changePassword(Long id, String oldPassword, String newPassword) {
        log.info("开始修改密码: userId={}", id);
        
        // 获取用户信息
        SysUser user = getById(id);
        if (user == null) {
            log.error("用户不存在: userId={}", id);
            throw new ServiceException("用户不存在");
        }

        // 验证旧密码
        boolean matches = passwordEncoder.matches(oldPassword, user.getPassword());
        log.info("密码验证结果: userId={}, matches={}", id, matches);
        
        if (!matches) {
            log.warn("当前密码不正确: userId={}", id);
            throw new ServiceException("当前密码不正确");
        }

        // 更新密码
        try {
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdateTime(LocalDateTime.now());
            updateById(user);
            log.info("密码修改成功: userId={}", id);
        } catch (Exception e) {
            log.error("密码修改失败: userId={}, error={}", id, e.getMessage());
            throw new ServiceException("密码修改失败");
        }
    }

    /**
     * 根据角色标识获取角色ID
     */
    private Long getRoleId(String roleKey) {
        // 根据角色key查询角色
        SysRole role = roleMapper.selectOne(
            new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleKey, roleKey)
        );
        // 如果角色不存在，抛出异常
        if (role == null) {
            throw new ServiceException("角色不存在: " + roleKey);
        }
        // 返回角色id
        return role.getId();
    }

    @Override
    public boolean existsByEmail(String email) {
        // 根据邮箱查询用户是否存在
        return lambdaQuery()
                // 等于邮箱
                .eq(SysUser::getEmail, email)
                // 未删除
                .eq(SysUser::getDeleted, 0)
                // 判断是否存在
                .exists();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(String email, String newPassword) {
        // 记录开始通过邮箱重置密码的日志
        log.info("开始通过邮箱重置密码: email={}", email);
        
        // 查找用户
        SysUser user = lambdaQuery()
                .eq(SysUser::getEmail, email)
                .eq(SysUser::getDeleted, 0)
                .one();
                
        // 如果用户不存在，抛出异常
        if (user == null) {
            log.error("用户不存在: email={}", email);
            throw new ServiceException("用户不存在");
        }

        try {
            // 加密新密码
            String encodedPassword = passwordEncoder.encode(newPassword);
            
            // 更新密码
            user.setPassword(encodedPassword);
            user.setUpdateTime(LocalDateTime.now());
            updateById(user);
            
            // 记录密码重置成功的日志
            log.info("密码重置成功: userId={}", user.getId());
        } catch (Exception e) {
            // 记录密码重置失败的日志
            log.error("密码重置失败: userId={}, error={}", user.getId(), e.getMessage());
            throw new ServiceException("密码重置失败");
        }
    }

    /**
     * 保存注册日志
     */
    private void saveRegisterLog(Long userId, String username, String role, String status) {
        SysRegisterLog log = new SysRegisterLog();
        log.setUserId(userId);
        log.setUsername(username);
        log.setRole(role);
        log.setStatus(status);
        
        // 获取当前请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        
        // 获取IP地址
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        
        // 判断是否为本地IP
        if (isLocalIpAddress(ipAddress)) {
            log.setLocation("本地开发环境");
        } else {
            log.setLocation(""); // 暂时为空，后续可以添加IP地址解析
        }
        
        log.setIp(ipAddress);
        
        // 获取User-Agent信息
        String userAgent = request.getHeader("User-Agent");
        
        // 自定义操作系统检测
        String osInfo = detectOperatingSystem(userAgent);
        log.setOs(osInfo);
        
        // 设置设备类型
        log.setDeviceType(detectDeviceType(userAgent));
        
        log.setCreateTime(LocalDateTime.now());
        
        registerLogMapper.insert(log);
    }

    /**
     * 自定义操作系统检测
     */
    private String detectOperatingSystem(String userAgent) {
        if (userAgent == null) {
            return "Unknown";
        }
        
        // Windows 11 检测
        if (userAgent.contains("Windows NT 10.0") && !userAgent.contains("Windows NT 10.0; Win64")) {
            return "Windows 11";
        }
        
        // 其他 Windows 版本
        if (userAgent.contains("Windows NT 10.0")) {
            return "Windows 10";
        }
        if (userAgent.contains("Windows NT 6.3")) {
            return "Windows 8.1";
        }
        if (userAgent.contains("Windows NT 6.2")) {
            return "Windows 8";
        }
        if (userAgent.contains("Windows NT 6.1")) {
            return "Windows 7";
        }
        
        // macOS
        if (userAgent.contains("Mac OS X")) {
            String version = extractMacVersion(userAgent);
            return "macOS " + version;
        }
        
        // Linux
        if (userAgent.contains("Linux")) {
            if (userAgent.contains("Ubuntu")) {
                return "Ubuntu";
            }
            if (userAgent.contains("Fedora")) {
                return "Fedora";
            }
            return "Linux";
        }
        
        // 移动设备
        if (userAgent.contains("iPhone")) {
            return "iOS";
        }
        if (userAgent.contains("Android")) {
            return "Android";
        }
        
        return "Unknown";
    }

    /**
     * 提取 macOS 版本号
     */
    private String extractMacVersion(String userAgent) {
        // Mac OS X 10_15_7 格式
        int start = userAgent.indexOf("Mac OS X") + 9;
        int end = userAgent.indexOf(")", start);
        if (start > 8 && end > start) {
            String version = userAgent.substring(start, end)
                .replace("_", ".")
                .trim();
            return version;
        }
        return "";
    }

    /**
     * 判断是否为本地IP
     */
    private boolean isLocalIpAddress(String ip) {
        return "127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip) || "localhost".equals(ip);
    }

    @Override
    public String getRealName(Long userId) {
        SysUser user = getById(userId);
        return user != null ? user.getRealName() : null;
    }

    @Override
    public List<Long> getUserIdsByUsername(String username) {
        return lambdaQuery()
            .like(SysUser::getUsername, username)
            .select(SysUser::getId)
            .list()
            .stream()
            .map(SysUser::getId)
            .collect(Collectors.toList());
    }

    /**
     * 检测设备类型
     */
    private String detectDeviceType(String userAgent) {
        if (userAgent == null) {
            return "Unknown";
        }
        
        // 移动设备
        if (userAgent.contains("Mobile") || 
            userAgent.contains("Android") || 
            userAgent.contains("iPhone") || 
            userAgent.contains("iPad") || 
            userAgent.contains("iPod")) {
            return "Mobile";
        }
        
        // 平板设备
        if (userAgent.contains("Tablet") || 
            userAgent.contains("iPad")) {
            return "Tablet";
        }
        
        // 默认为桌面设备
        return "Desktop";
    }
} 